package com.zhanglijie.improve.collections.concurrenthashmap.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

import com.zhanglijie.improve.collections.concurrenthashmap.MyConcurrentHashMap;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/11/6 0006 16:13
 *
 * 演示HashMap的不安全问题：根源hashcode相同同时执行   if ((p = tab[i = (n - 1) & hash]) == null)
 *                                                tab[i] = newNode(hash, key, value, null);
 *                                                }
 *
 *  换成ConcurrntHashMap就不会存在安全问题
 */
public class UnsafeDemo1 {
    public static void main(String[] args) throws InterruptedException {
        for (int cur = 0; cur < 20000; cur++) {
            ArrayList<Task> tasks = new ArrayList<>();
            tasks.add(new Task());
            tasks.add(new Task());
            System.out.println("list size: "+tasks.size());

            MyConcurrentHashMap<Task, Integer> map = new MyConcurrentHashMap<>();  //安全
           // Map<Task, Integer> map = new HashMap<>();
            CountDownLatch count = new CountDownLatch(2);
            for (int i = 0; i < tasks.size(); i++) {
                int finalI = i;
                new Thread(()->{
                    map.put(tasks.get(finalI),finalI);
                    count.countDown();
                }).start();
            }

            count.await();
            System.out.println("map size: "+map.size());
            if(map.size() == 1){
                break;
            }
        }
    }

    static class Task{
        @Override
        public int hashCode(){
            return 1;
        }
    }
}
